#include "led_sw.h"
#include "beep.h"

volatile U8         v_ReloadTimer2;
volatile ePulseType v_PulseType;


void Beep_InitReset(void)
{
    //init timer2 voi prescale = 16 de su dung cho PWM
    TMR2IF = 0;
    T2CON = 0x02;       // prescale = 16

    // Cau hinh cho PWM
    // cho do dai muc 1 la co dinh = PWM_ALARM_PERIOD_MIN/2
    // tan so cua PWM la do thanh ghi PR2 quyet dinh
    CCP1CON = 0x0C;
    PR2 = v_ReloadTimer2 = PWM_ALARM_MIN_PR2;
    CCPR1L = PWM_ALARM_MIN_CCPR1L;
    CCP1CONbits.DC1B = PWM_ALARM_MIN_DC1B;

    BEEP_TRIS = 0;
}

void Beep_OnAlarm(void)
{
    Beep_SetPeriodInterrupt(PWM_ALARM_MAX_PR2);
    Beep_SetPulseType(DEC_TYPE);
    Beep_TurnOnPwm();
}

void Beep_OnBeep(void)
{
    Beep_SetPeriod(PWM_BEEP_PR2);
    Beep_TurnOnPwm();
}

void Beep_OnBellBing(void)
{
    Beep_SetPeriod(PWM_BELL_BING_PR2);
    Beep_TurnOnPwm();
}

void Beep_OnBellBong(void)
{
    Beep_SetPeriod(PWM_BELL_BONG_PR2);
    Beep_TurnOnPwm();
}

void Beep_TurnOff(void)
{
    Beep_TurnOffPwm();
}

#ifdef TESTING_MODE
void Beep_SetBeepType( eBeepType iBeepType)
{
    switch ( iBeepType )
    {
    default:
    case BEEP_BEEP:
        {
            Beep_OnBeep();
            __delay_ms(BEEP_BLOCKING_SHORT_TIMER);
            Beep_TurnOff();
        } break;
      
    case BEEP_BEEP_LONG:
        {
            Beep_OnBeep();
            __delay_ms(BEEP_BLOCKING_LONG_TIMER);
            Beep_TurnOff();
        } break;

    case BEEP_BEEP2:
        {
            Beep_OnBeep();
            __delay_ms(BEEP2_ON_BLOCKING_TIMER);
            Beep_TurnOff();
            __delay_ms(BEEP2_OFF_BLOCKING_TIMER);
            Beep_OnBeep();
            __delay_ms(BEEP2_ON_BLOCKING_TIMER);
            Beep_TurnOff();
        } break;

    case BEEP_BEEP3:
        {
            Beep_OnBeep();
            __delay_ms(BEEP3_ON_BLOCKING_TIMER);
            Beep_TurnOff();
            __delay_ms(BEEP3_OFF_BLOCKING_TIMER);
            Beep_OnBeep();
            __delay_ms(BEEP3_ON_BLOCKING_TIMER);
            Beep_TurnOff();
            __delay_ms(BEEP3_OFF_BLOCKING_TIMER);
            Beep_OnBeep();
            __delay_ms(BEEP3_ON_BLOCKING_TIMER);
            Beep_TurnOff();
        } break;

    case BEEP_BELL:
        {
            Beep_OnBellBing();
            __delay_ms(BELL_BLOCKING_TIMER1);
            Beep_OnBellBong();
            __delay_ms(BELL_BLOCKING_TIMER2);
            Beep_TurnOff();
        } break;
        
    case BEEP_BELL_ON_LED:
        {
            Beep_OnBellBing();
            ON_LED;
            __delay_ms(BELL_BLOCKING_TIMER1);
            Beep_OnBellBong();
            OFF_LED;
            __delay_ms(BELL_BLOCKING_TIMER2);
            Beep_TurnOff();
        } break;
    }
}
#endif

